package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
import android.widget.ImageView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;

import com.google.gson.Gson;
import com.mob.MobSDK;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.bean.TeacherVideoResponse;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.MyWebViewClient;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.R;

//视频webview
@SuppressLint({ "InlinedApi", "NewApi" })
public class VideoWebActivity extends Activity implements OnClickListener {

	private ImageView iv_back;
	private Intent intent;
	private String rowid;
	private String url;
	private WebView mWebView;
	private String account;
	private String role;
	private String title;
	private ImageView iv_share;

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_videoweb);
		intent = getIntent();
		rowid = intent.getStringExtra("row_id");
		url = intent.getStringExtra("url");
		title = intent.getStringExtra("title");
		account = SPUtil.getString(this, "account", "");
		role = SPUtil.getString(this, "role", "");

		initView();
		initWebView();
		setOnListener();
		initData();

	}

	private void initWebView() {
		WebSettings settings = mWebView.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setJavaScriptCanOpenWindowsAutomatically(true);
		settings.setPluginState(PluginState.ON);
		// settings.setPluginsEnabled(true);
		settings.setAllowFileAccess(true);
		settings.setLoadWithOverviewMode(true);

		// settings.setSupportZoom(true);
		// mWebView.requestFocusFromTouch();
		// settings.setUseWideViewPort(true);// 可任意比例缩放
		// settings.setBuiltInZoomControls(true);
		// settings.setSavePassword(true);
		// settings.setSaveFormData(true);// 保存表单数据
		// settings.setDomStorageEnabled(true);//
		// settings.setSupportMultipleWindows(true);// 新加
		// settings.setAppCacheEnabled(true);
		// settings.setCacheMode(WebSettings.LOAD_DEFAULT);
		// settings.setDatabaseEnabled(true);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
		}
		mWebView.setWebChromeClient(new WebChromeClient());
		mWebView.setWebViewClient(new WebViewClient());
		// mWebView.setWebChromeClient(new WebChromeClient() {
		// @Override
		// public void onProgressChanged(WebView view, int newProgress) {
		// // TODO Auto-generated method stub
		// // MainActivity.this.setProgress(newProgress * 100);
		// }
		//
		//
		// });
	}

	private void initView() {
		// TODO Auto-generated method stub
		iv_back = (ImageView) findViewById(R.id.iv_back);
		mWebView = (WebView) findViewById(R.id.wb_video);
		iv_share = (ImageView) findViewById(R.id.iv_share);

		if ("1".equals(role)) {
			iv_share.setVisibility(iv_share.GONE);
		}
	}

	private void initData() {
		mWebView.reload();
		// mWebView.loadUrl("https://v.youku.com/v_show/id_XMzExMzg2NjY0OA==.html?spm=a2h3j.8428770.3416059.1");
		mWebView.loadUrl(url);

		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				// 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器

				if (url == null)
					return false;

				try {
					if (url.contains("youku") //
					) {
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri
								.parse(url));
						startActivity(intent);
						// finish();
						return false;
					}
				} catch (Exception e) { // 防止crash
										// (如果手机上没有安装处理某个scheme开头的url的APP,
										// 会导致crash)
					Log.e("test", e.toString());
					return true;// 没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
				}

				view.loadUrl(url);
				return true;
			}
		});

		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "27");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("showid", rowid);
		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			// http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=26&c=18271261779&role=2&vtype=0
			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();
				String json = arg0.body().string();
				Log.e("test", json);

			}
		});
	}

	private void setOnListener() {
		iv_back.setOnClickListener(this);
		iv_share.setOnClickListener(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		mWebView.onPause();
		mWebView.pauseTimers();
	}

	@Override
	public void onResume() {
		super.onResume();
		mWebView.resumeTimers();
		mWebView.onResume();
	}

	@Override
	protected void onDestroy() {
		mWebView.destroy();
		mWebView = null;
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.iv_share:
			if (title == null && TextUtils.isEmpty(title)) {
				title = "视频";
			}

			clickShare(v);
			break;
		}
		
	}

	private void clickShare(View v) {

		// TODO Auto-generated method stub
		MobSDK.init(VideoWebActivity.this, "12c24ea0b59b0",
				"aae63565fbd69b1acbfcdd0d5ac0b35c");
		OnekeyShare oks = new OnekeyShare();
		// 关闭sso授权
		oks.disableSSOWhenAuthorize();
		oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

			@Override
			public void onShare(Platform platform, ShareParams paramsToShare) {
				if (SinaWeibo.NAME.equals(platform.getName())) {
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用

					// String title1 = title+"来自金牌君App 教师风采";
					int unicodeJoy = 0x1F44D;
					String emojiString = new String(Character
							.toChars(unicodeJoy));
					paramsToShare.setTitleUrl(url);
					// paramsToShare.setTitleUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					paramsToShare.setTitle(title + "来自金牌君App 教师风采");
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText("金牌新概念");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/applogo.png");
					// paramsToShare.setImageData(mBitmap);
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare.setUrl(url);
					// paramsToShare.setUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					// paramsToShare.setSite(getString(R.string.app_name));
					paramsToShare.setSite("金牌君");
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare.setSiteUrl(url);
					// paramsToShare.setSiteUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);

				} else {
					paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					paramsToShare.setTitleUrl(url);
					// paramsToShare.setTitleUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					paramsToShare.setTitle(title + "来自金牌君App 教师风采");
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText("金牌新概念");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/applogo.png");

					// paramsToShare.setImageData(mBitmap);
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare.setUrl(url);
					// paramsToShare.setUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					paramsToShare.setSite("金牌君");
					// paramsToShare.setSite(getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare.setSiteUrl(url);
					// paramsToShare.setSiteUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);

				}
			}
		});

		// 启动分享GUI
		oks.show(this);
	}

}
